<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\StudentClass;
use App\Model\Student;
use App\Model\Feedback;
use App\Model\Attachment;
use Illuminate\Support\Facades\Storage;
use Validator;

/**
 * 班级
 */
class ClassController extends Controller
{
    // 列表
    public function index(Request $request)
    {
        $class_type = $request->class_type ?: 0;
        $year = $request->year ?: 0;
        $begin_time = $request->begin_time ?: '';
        $end_time = $request->end_time ?: '';
        $search = $request->search ?: '';
        $page_size = $request->page_size ?: 10;
        $sort = $request->sort ?: '-id';
        $student_number = $request->student_number ?: 0; // 学生数量参数
        $feedback_number = $request->feedback_number ?: 0; // 反馈数量参数

        $search = trim($search);

        $query = StudentClass::select('id', 'class_type', 'year', 'class_name', 'class_start_time', 'class_fee', 'max_num', 'sign_start_time', 'sign_end_time', 'remarks');

        if ($class_type !== 0) {
            $query->where('class_type', $class_type);
        }
        if ($year !== 0) {
            $query->where('year', $year);
        }
        if ($begin_time !== '') {
            $query->where('class_start_time', '>=', get_timestamp($begin_time));
        }
        if ($end_time !== '') {
            $query->where('class_start_time', '<=', get_timestamp(strtotime('+1 month', strtotime($end_time))));
        }
        if ($search !== '') {
            $query->where(function ($query) use ($search) {
                return $query->Orwhere('class_name', 'like', "%{$search}%");
            });
        }
        if ($sort[0] === '+') {
            $query->orderBy(substr($sort, 1), 'ASC');
        } else {
            $query->orderBy(substr($sort, 1), 'DESC');
        }
        $res = $query->paginate($page_size);

        $data = $res->getCollection();
        if ($student_number) {
            // 添加学生数量
            $data->map(function (&$item) {
                $item->student_number = Student::where('class_id', $item->id)->count();
            });
        }
        if ($feedback_number) {
            // 添加反馈数量
            $data->map(function (&$item) {
                $item->feedback_number = Feedback::where('class_id', $item->id)->count();
            });
        }

        return resJson(self::HTTP_0_SUCCESS, $res);
    }

    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_name' => [
                'required',
                // 'unique:sf_class', 
                'max:255'
            ],
            'year' => ['required'],
            'class_type' => ['required'],
        ], [
            'class_name.required' => '班级名称必填',
            'class_name.unique' => '班级名称不能重复',
            'year.required' => '年份必填',
            'class_type.required' => '类型必填',
        ]);
        if ($validator->fails()) {
            $errors = $validator->errors();
            return resJson(self::HTTP_500_ERROR, $errors->first());
        }
        $input = $request->all();
        if (isset($input['class_start_time'])) $input['class_start_time'] = get_timestamp($input['class_start_time']);
        if (isset($input['sign_start_time'])) $input['sign_start_time'] = get_timestamp($input['sign_start_time']);
        if (isset($input['sign_end_time'])) $input['sign_end_time'] = get_timestamp($input['sign_end_time']);
        $input['created_time'] = millisecond();
        $class = StudentClass::create($input);
        return resJson(self::HTTP_0_SUCCESS, $class);
    }

    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'class_name' => ['required', 'max:255'],
            'year' => ['required'],
            'class_type' => ['required'],
        ], [
            'class_name.required' => '班级名称必填',
            'year.required' => '年份必填',
            'class_type.required' => '类型必填',
        ]);
        if ($validator->fails()) {
            $errors = $validator->errors();
            return resJson(self::HTTP_500_ERROR, $errors->first());
        }
        $studentClass = StudentClass::find($id);
        $input = $request->all();
        unset($input['student_number']);
        if (isset($input['class_start_time'])) $input['class_start_time'] = get_timestamp($input['class_start_time']);
        if (isset($input['sign_start_time'])) $input['sign_start_time'] = get_timestamp($input['sign_start_time']);
        if (isset($input['sign_end_time'])) $input['sign_end_time'] = get_timestamp($input['sign_end_time']);
        $input['updated_time'] = millisecond();
        if ($studentClass) {
            $studentClass->fill($input);
            $studentClass->save();
            return resJson(self::HTTP_0_SUCCESS);
        } else {
            return resJson(self::HTTP_500_ERROR);
        }
    }

    public function upload(Request $request, $id)
    {
        if ($request->hasFile('photo') && $request->file('photo')->isValid()) {
            $photo = $request->file('photo');
            $path = $photo->store('photo', 'public'); // dirve is public
            $attachment = new Attachment();
            $attachment->class_id = $id;
            $attachment->file_name = $photo->getClientOriginalName();
            $attachment->file_path = $path;
            $attachment->file_size = $photo->getClientSize();
            $attachment->file_ext = $photo->getClientOriginalExtension();
            $attachment->http_path = env('APP_URL') . Storage::url($path);
            $attachment->created_time = millisecond();
            $attachment->save();
            return resJson(self::HTTP_0_SUCCESS, $attachment);
        }
        return resJson(self::CUSTOM_10003_UPLOAD_ERROR);
    }

    public function photo(Request $request)
    {
        $id = $request->id;
        $photos = Attachment::where('class_id', $id)->select('id', 'file_name', 'http_path')->get();
        return resJson(self::HTTP_0_SUCCESS, $photos);
        // if (Storage::disk('class')->exists($path)) {
        //     return Storage::disk('class')->get($path);
        //     // $path = str_replace("/", DIRECTORY_SEPARATOR, storage_path('app/class/' . $path));
        //     // return response()->file($path);
        // } else {
        //     return resJson(self::HTTP_500_ERROR);
        // }
    }

    public function destroyPhoto(Request $request)
    {
        $id = $request->id;
        $photo = Attachment::find($id);
        if ($photo) {
            Storage::disk('public')->delete($photo['file_path']);
        }
        $photo->delete();
        return resJson(self::HTTP_0_SUCCESS);
    }

    public function destroy($id)
    {
        if (Student::where('class_id', $id)->count()) {
            return resJson(self::CUSTOM_10006_NOEDIT_ERROR);
        }
        StudentClass::destroy($id);
        return resJson(self::HTTP_0_SUCCESS);
    }

    public function destroyAll(Request $request)
    {
        StudentClass::whereIn('id', $request->ids)->delete();
        return resJson(self::HTTP_0_SUCCESS);
    }
}
